<template>
  <Container class="role-edit">
    <div slot="header" class="container-header title title-center">
      {{ title }}
      <Button size="large" class="fl btn-back" icon="ios-arrow-back" @click="jumpPrevPage">返回</Button>
    </div>
    <div class="bgs bg-white">
      <div class="content">
        <div v-if="!this.id" class="item">
          <span class="common">业务员手机号:</span>
          <Input
            v-model.trim="mobile"
            class="input"
            maxlength="11"
            search
            enter-button
            placeholder="请输入业务员手机号"
            @on-search="getBasics"
          />
        </div>
        <div class="item">
          <span class="common">姓名:</span>
          <span>{{ basicsData.salesmanContractDTO.realname || '--' }}</span>
        </div>
        <div class="item">
          <span class="common">身份证号码:</span>
          <span>{{ basicsData.salesmanContractDTO.idCardNo||'--' }}</span>
        </div>
        <div class="item">
          <span class="common">昵称:</span>
          <span>{{ basicsData.salesmanContractDTO.nickName||'--' }}</span>
        </div>
        <div class="item">
          <span class="common">登录手机:</span>
          <span>{{ basicsData.salesmanContractDTO.mobile||'--' }}</span>
        </div>
        <div class="item">
          <span class="common">品牌:</span>
          <CheckboxGroup v-model="checkBrandList" @on-change="checkboxGroup">
            <Checkbox
              v-for="(item ,index) in brandList"
              :key="index"
              :label="item.brandId"
            >{{ item.brandName }}</Checkbox>
          </CheckboxGroup>
        </div>
        <div class="item">
          <span class="common">职能类型:</span>
          <Select v-model="roleInfo.roleId" class="select">
            <Option v-for="item in roleList" :key="item.id" :value="item.id">{{ item.roleName }}</Option>
          </Select>
        </div>
        <div class="item">
          <span class="common">选择方式:</span>
          <Tabs v-model="tab" type="card" size="small">
            <TabPane label="按部门选择" name="tab1" />
            <TabPane label="按经销商选择" name="tab2" />
          </Tabs>
        </div>
        <div class="tab-container">
          <Department
            v-show="tab=='tab1'"
            ref="department"
            :has-department-data="allHasDepartment"
            @onCheckChange="onCheckChange"
            @onChange="onChange"
          />
          <Dealers
            v-show="tab=='tab2'"
            :ref="form"
            :distributor-data="allDistributor"
            :has-distributor-data="allHasDistributor"
            @sendParentData="dealDistributorData"
          />
        </div>
        <div class="tab-container">
          <!-- <span class="common">业务区域:</span>
          <OperationArea
            ref="OperationArea"
            :checked-id-list="areaIdList"
            @checkChangeArea="onCheckChangeTree"
          /> -->
           <AreaTree
              ref="treeadd"
              class="mb"
              :checkedIdList="checkedIdList"
              @onCheckChange="onCheckChangeTree"
              customerClass="treeplc"
            />
        </div>
      </div>
    </div>
    <Loader :status="status" @refresh="getInfo" />
    <div slot="footer" class="container-footer bg-white">
      <div>
        <Button type="primary" class="mr" size="large" @click="onSave">保存</Button>
        <Button type="primary" class="mr" size="large" @click="jumpPrevPage">取消</Button>
      </div>
    </div>
  </Container>
</template>
<script>
import table from '@/table'
import homeTable from '@/components/homeTable'
import Department from './edit/DepartmentEditItem'
import Dealers from './edit/DealersEditItem'
import OperationArea from './edit/OperationArea'
import AreaTree from '@/components/AreaTree';
import listData from './edit/factoryEditItemData'
import { getOriginData } from '@/util'
import data from '../../policy/brandException/list/BrandExceptionListData'
export default {
  components: {
    homeTable,
    Department,
    Dealers,
    OperationArea,
    AreaTree
  },
  data () {
    return {
      id: this.$route.query.id || '',
      title: '签约业务员',
      rules: {
        name: [{ required: true, message: '不能为空', trigger: 'blur' }]
      },
      tab: 'tab2',
      // btnDisabled:false,
      // form: {
      //   name: ""
      // },
      basicsData: {
        departmantIds: [],
        salesmanContractDTO: {},
        supplierDepartmentVOs: []
      },
      brandList: [],
      roleList: [],
      checkBrandList: [],
      allDepartment: [],
      allDistributor: [],
      sonHasList: [],
      getAreaList: [],
      sonHasDealDistributor: [],
      allHasArea: [],
      sonAreaList: [],
      checkBrandData: [],
      allHasDepartment: [],
      areaIdList: [],
      allHasDistributor: [],
      roleInfo: { roleId: '', roleName: '' },
      flag: false,
      single: false,
      status: 'pass',
      checkedIdList:[],
      ...listData,
      result: []
    }
  },
  computed: {
    roleitem () {
      // 选中的角色
      return this.roleList.find(item => item.id == this.roleInfo.roleId) || {}
    }
  },
  mounted () {
    if (this.$route.query.id) {
      this.getEditData()
    } else {
      this.getBrandList()
    }
    // this.getRoleData();
  },
  created () {
    this.getRoleData()
  },
  methods: {
    jumpPrevPage () {
      this.$router.back()
    },
    cancle () {
      this.$router.back()
    },
    checkboxGroup (data) {
      if (!this.basicsData.salesmanContractDTO.salesmanId) return
      let param = {
        brandIds: data,
        salesmanId: this.id
          ? this.basicsData.salesmanContractDTO.salesmanId
          : this.basicsData.salesmanContractDTO.id
      }
      this.$ajaxGet('/department/findDistributorBySupplier', param).then(
        res => {
          this.allDistributor = res
        }
      )
      this.checkBrandData = this.brandList.filter(it => {
        const x = data.find(v => {
          return v == it.brandId
        })
        return !!x
      })
    },
    // 处理部门已授权数据
    onCheckChange (val) {
      if (val.length === 0) {
        this.sonHasList = []
        this.flag = true
      } else {
        let parentValue = val.filter((e) => e.level == 1)
        let sonValue = val.filter((e) => e.level == 2)
        let newArr = sonValue.filter(   e=> {
          return !parentValue.find(s => s.id == e.parentId)
        } )
        this.sonHasList =parentValue.concat(newArr).map(item=>{
          return{
                departmentId: item.id,
                departmentName: item.name,
                distributorId: 0
          }
        })
        this.flag = true
      }
    },
    // 区域选中数据
     onCheckChangeTree (val) {
      this.result = []
       if(val.length && !val[0].nodeKey){
         this.result = val[0].children.map(e=>{
           return{
              adcode: e.adcode,
              treePath: e.treePath,
              areaId :e.id,
              areaName: e.name
           }
         })
         return;
       }
      this.checkList = val.slice()
      this.repeat()
      this.result = this.result.map(e=>{
        return {
          adcode: e.adcode,
          treePath: e.treePath,
          areaId :e.id,
          areaName: e.name
        }
      })
    },
    repeat () {
      for (var i = 0; i < this.checkList.length; i++) {
        this.format(this.checkList[i])
      }
    },
    format (item) {
      this.result.push(item)
      this.checkList = this.checkList.filter(it => !it.treePath.split(',').includes(item.id) && it.id !== item.id)
      this.repeat()
      
    },
    onChange (single) {
      this.single = single
    },
    // 处理经销商已授权数据
    dealDistributorData (data) {
      this.sonHasDealDistributor = data.map(it => {
        return {
          departmentId: it.secondaryDepartmentId,
          departmentName: it.secondaryDepartmentName,
          distributorId: it.distributorId,
          distributorName: it.distributorName
        }
      })
    },
    // 编辑工厂业务员基础信息
    async getEditData () {
      if (!this.id) return
      let param = {
        contractId: this.id
      }
      this.status = 'loading'
      await this.$ajaxGet('/supplier_salesman/contractInfo', param).then(
        data => {
          this.basicsData.salesmanContractDTO = data
          data.salesmanContractBrandDTOS.forEach(it => {
            this.checkBrandList.push(Number(it.brandId))
          })
          this.roleInfo.roleId = data.roleId
          this.roleInfo.roleName = data.roleName
          this.checkBrandData = data.salesmanContractBrandDTOS.map(it => {
            return {
              brandId: it.brandId,
              brandName: it.brandName
            }
          })
          this.status = 'pass'
        }
      )
      await this.getBrandList()
      await this.getEditHasData()
      await this.getEditHasDistributor()
      await this.getEditHasAreaData()
      await this.getChoiceDistributorData()
    },

    // 获取编辑已授权的部门数据
    getEditHasData () {
      if (!this.id) return
      let param = {
        salesmanId: this.basicsData.salesmanContractDTO.salesmanId
      }
      return this.$ajaxGet('/supplier_salesman/contractDepartment', param).then(
        data => {
          this.allHasDepartment = data
        }
      )
    },
    // 获取已授权的区域数据
    getEditHasAreaData () {
      let param = {
        salesmanId: this.basicsData.salesmanContractDTO.salesmanId
      }
      return this.$ajaxGet('/supplier_salesman/contractArea', param).then(
        data => {
          this.checkedIdList = (data || []).map(e => e.areaId)
          this.result = data
        })
    },

    // 获取已授权经销商数据
    getEditHasDistributor () {
      if (!this.id) return
      let param = {
        salesmanId: this.basicsData.salesmanContractDTO.salesmanId
      }
      return this.$ajaxGet(
        '/supplier_salesman/contractDistributor',
        param
      ).then(data => {
        this.allHasDistributor = data
      })
    },

    //获取基础数据
    async getBasics () {
      if (!this.mobile) {
        this.$Message.error('请输入业务员手机号码搜索！')
        return
      }
      this.status = 'loading'
      let param = {
        mobile: this.mobile || ''
      }
      await this.$jsonPost('/supplier_salesman/mobile/exists', param)
        .then(data => {
          if (!data.departmantIds && !data.supplierDepartmentVOs) {
            this.basicsData = data
            this.roleInfo.roleId = ''
            this.roleInfo.roleName = ''
            this.allHasDistributor = []
            this.allHasArea = []
            this.getAllCheckBrandList()
            setTimeout(() => {
              this.getChoiceDistributorData()
              this.getEditHasAreaData()
            }, 500)
            this.status = 'pass'
          } else {
            this.basicsData = data;
            (this.roleInfo.roleId = data.salesmanContractDTO.roleId),
            (this.roleInfo.roleName = data.salesmanContractDTO.roleName)
            this.checkBrandData = data.salesmanContractDTO.salesmanContractBrandDTOS.map(
              it => {
                return {
                  brandId: it.brandId,
                  brandName: it.brandName
                }
              }
            )
            this.checkBrandList = this.checkBrandData.map(it => {
              return Number(it.brandId)
            })
            this.allHasDistributor = data.supplierDepartmentVOs || []
            this.allHasDepartment = data.departmantIds || []
            this.getChoiceDistributorData()
            this.getEditHasAreaData()
          }
          this.status = 'pass'
        })
        .catch(() => {
          this.status = 'pass'
        })
    },
    // 获取所有品牌接口
    getBrandList () {
      return this.$ajaxGet('/product/common/supplier_brand').then(data => {
        this.brandList = data.map(it => {
          return {
            brandName: it.brandName,
            brandId: Number(it.brandId)
          }
        })
      })
    },
    // 新增第一次进入默认选中所有品牌
    getAllCheckBrandList () {
      return this.$ajaxGet('/product/common/supplier_brand').then(data => {
        this.brandList = data.map(it => {
          return {
            brandName: it.brandName,
            brandId: Number(it.brandId)
          }
        })
        data.forEach(it => {
          this.checkBrandList.push(Number(it.brandId))
        })
        this.checkBrandData = this.brandList
      })
    },

    // 获取按经销商选择类型的接口
    getChoiceDistributorData () {
      let param = {
        brandIds: this.checkBrandList || [],
        salesmanId: this.basicsData.salesmanContractDTO.salesmanId
      }
      this.$ajaxGet('/department/findDistributorBySupplier', param).then(
        data => {
          this.allDistributor = data
        }
      )
    },
    // 获取职能类型接口
    getRoleData () {
      this.$ajaxGet('/supplier_salesman/findRoles').then(data => {
        this.roleList = data
      })
    },
    onSave () {
      if (this.btnDisabled) return
      this.btnDisabled = true
      // this.$refs["form"].validate(valid => {
      // if (valid) {
      let text = this.basicsData.salesmanContractDTO.id ? '编辑' : '新增'
      let url = '/supplier_salesman/contract'
      // 区别部门还是经销商已授权数据
      let whatData = ''
      if (this.tab == 'tab2') {
        whatData = this.sonHasDealDistributor
        let hasFilterList = []
        hasFilterList = this.allHasDistributor
          .filter(e => !e.unsign)
          .map(it => {
            return {
              departmentId: it.secondaryDepartmentId,
              departmentName: it.secondaryDepartmentName,
              distributorId: it.distributorId,
              distributorName: it.distributorName
            }
            return it
          })
        whatData = whatData.concat(hasFilterList)
      } else {
        if (this.flag) {
          whatData = this.sonHasList
        } else {
          whatData = this.allHasDepartment.map(it => {
            return {
              departmentId: it,
              distributorId: 0
            }
          })
        }
      }
      let param = {
        isWhole: this.tab == 'tab1' ? (!!this.single) : null,
        salesmanContractDTOs: [
          {
            // id: this.id ? this.id : "",
            id: this.basicsData.salesmanContractDTO.id
              ? this.basicsData.salesmanContractDTO.id
              : '',
            salesmanId: this.basicsData.salesmanContractDTO.salesmanId,
            distributorId: 0,
            flag: this.tab == 'tab1' ? 0 : 1,
            realname: this.basicsData.salesmanContractDTO.realname || '',
            roleId: this.roleitem.id,
            roleName: this.roleitem.roleName,
            salesmanContractBrandDTOS: this.checkBrandData || [],
            salesmanDepartmentDTOS: this.single ? [] : (whatData || []),
            salesmanContractAreaDTOS: this.result
          }
        ]
      }
      this.$jsonPost(url, param)
        .then(data => {
          this.$Notice.success({
            title: `${text}成功`
          })
          this.$router.push('/setting/factory/list')
        })
        .catch(() => {
          this.btnDisabled = false
        })
      // } else {
      //   this.btnDisabled = false;
      // }
      // });
    }
  }
}
</script>
